package repository

import (
	"github.com/google/uuid"
	"gorm.io/gorm"

	"forum/pkg/domain"
)

type threadRepository struct {
	DB *gorm.DB
}

func NewThreadRepository(db *gorm.DB) domain.ThreadRepository {
	return &threadRepository{
		DB: db,
	}
}

func (rep *threadRepository) CreateThread(thread *domain.Thread) error {
	// create uuid for User
	thread.UUID = uuid.New().String()

	return rep.DB.Create(thread).Error
}

func (rep *threadRepository) DeleteThread(threadID string) error {
	return rep.DB.Delete(&domain.Thread{}, threadID).Error
}

func (rep *threadRepository) GetThreads() ([]domain.Thread, error) {
	threads := make([]domain.Thread, 0)
	err := rep.DB.Find(&threads).Error
	return threads, err
}

func (rep *threadRepository) GetThreadByTopic(name string) (domain.Thread, error) {
	t := domain.Thread{}
	err := rep.DB.Where("name = ?", name).First(&t).Error
	return t, err
}
